package cn.wl.crm.web.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Controller
@RequestMapping("/file")
@CrossOrigin
public class FileUploadController {

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    public String upload(MultipartFile file) throws IOException {
        //完成上传

        /** 核心步骤：
         *  fastdfs 七牛云
         * (1) 构造一个新的文件
         *
         */
        String path ="H:\\otherSoftWare\\NODE\\node_workspace\\crm_parent\\crm_web\\src\\main\\webapp\\upload";
        //获取文件名字
        String fileName = file.getOriginalFilename();//xxx.jpg
        //获取文件后缀
           String extendsion =  FilenameUtils.getExtension(fileName);
        String newfileName = UUID.randomUUID().toString()+"."+extendsion;
        File newfile = new File(path,newfileName);

         //(2) 把前台传递过来的对象 写到新的文件
        //inputstrem outputstream
        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(newfile);
        IOUtils.copy(is,os);

        //(3) 把图片地址 返回到前端 前端拿到地址 --存入到数据库
        return "/upload/"+newfileName;



    }
}
